<template>
  <div class="top">
    <el-form :inline="true" size="default">
      <el-form-item>
        <el-select default v-model="queryParams.jobGroup" @change="groupChange" filterable placeholder="请选择执行器" clearable>
          <el-option value="0" key="0" label="全部"></el-option>
          <el-option
            v-for="item in groupListData"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select style="width: 200px;" default v-model="queryParams.jobId" placeholder="请选择任务" clearable>
          <el-option key="0" value ="0" label="全部"></el-option>
          <el-option
            v-for="item in jobs"
            :key="item.id"
            :label="item.jobDesc"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select style="width: 100px;" default v-model="queryParams.logStatus" placeholder="请选择日志状态">
  <!--            <el-option value="" label="全部"></el-option>-->
          <el-option
            v-for="item in statusEnum"
            :key="item.code"
            :label="item.msg"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="queryParams.timeScope"
          type="datetimerange"
          range-separator="~"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="pickerOptions.shortcuts"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getLogList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="clearJobLogs">清除日志</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref='list'
      :key='tableKey'
      :data="logTableList"
      v-loading="listLoading"
      element-loading-text="数据加载中，请稍后"
      border
      fit
      highlight-current-row
      select-on-indeterminate
      style="width: 100%">

      <el-table-column align="center" label="任务ID" min-width="60">
        <template slot-scope="scope">
          <el-button type="text" @click="jobDetail(scope.row)">{{scope.row.jobId}}</el-button>
        </template>
      </el-table-column>
<!--      <el-table-column align="center" label="任务名称" min-width="80">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.title}}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="调度时间" min-width="120">
        <template slot-scope="scope">
          <span class="link-type">{{formartHandlerTime(scope.row.triggerTime)}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="调度结果" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :class="{'sucColor':scope.row.triggerCode===200,'failColor':scope.row.triggerCode===500}">
            {{scope.row.triggerCode===200?'成功':(scope.row.triggerCode===500?'失败':'')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="调度备注" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" @click="triggerMsgDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="执行时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{formartHandlerTime(scope.row.handleTime)}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="执行结果" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :class="{'sucColor':scope.row.handleCode===200,'failColor':scope.row.handleCode===500}">
            {{scope.row.handleCode===200?'成功':(scope.row.handleCode===500?'失败':'')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="执行备注" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.handleMsg===''?'无':scope.row.handleMsg}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="60">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" v-show="scope.row.triggerCode===200" @click="exeLogDetail(scope.row)">日志详情</el-button>
          <el-button size="mini" type="danger" v-show="scope.row.triggerCode===200 && scope.row.handleCode===0"
                     @click="handleStopJob(scope.row.id)">终止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="queryParams.currentPage"
                     :page-sizes="[10,20,30,50]" :page-size="queryParams.length"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      class="dialog-detail-view"
      title="执行日志"
      custom-class="detail-dialog"
      width="60%"
      center
      @close="onCloseDetail">
        <pre v-html="jobLogDetail.logContent"></pre>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="清除执行器日志" v-model="clearLogDialog" center>
      <el-form :model="clearForm" label-width="100px" :rules="rules" ref="clearForm">
        <el-form-item class="clear-log-form-view" label="执行器" prop="jobGroup">
          <el-select v-model="clearForm.jobGroup" @change="groupClearChange" placeholder="请选择执行器">
            <el-option value="0" key="0" label="全部"></el-option>
            <el-option
              v-for="item in groupListData"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="clear-log-form-view" label="任务" prop="jobId" clearable>
          <el-select v-model="clearForm.jobId" placeholder="请选择任务">
            <el-option value="0" key="0" label="全部"></el-option>
            <el-option
              v-for="item in clearJobs"
              :key="item.id"
              :label="item.jobDesc"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="clear-log-form-view" label="清理方式" prop="type">
          <el-select v-model="clearForm.type" placeholder="请选择清理方式">
            <el-option
              v-for="item in logTimeEnum"
              :key="item.code"
              :label="item.msg"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <!--
        <el-form-item class="clear-log-form-view" label="状态" prop="logStatus">
          <el-select size="small" v-model="clearForm.logStatus" placeholder="请选择日志状态">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in statusEnum"
              :key="item.code"
              :label="item.msg"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearLogDialog = false">取 消</el-button>
        <el-button type="primary" @click="exeClearLogs">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import qs from 'qs'
import { formartUstTime } from "@/utils/index.js"
import { ElMessage, ElMessageBox } from 'element-plus'
import {getGroupList,clearLogs, getJobDetail, getLogsList, stopJob,getJobsByGroupLogs} from '@/api/scheduler'

const statusEnum = ref([
  {code:-1,msg:'全部'}, 
  {code: 1, msg: '成功'}, 
  {code: 2, msg: '失败'}, 
  {code: 3, msg: '进行中'}
])

const groupListData = ref([])
const jobs = ref([])
const clearJobs = ref([])
const dialogFormVisible = ref(false)
const clearLogDialog = ref(false)
const logTableList = ref(null)
const total = ref(null)
const listLoading = ref(true)

const queryParams = ref({
  currentPage: 1,
  jobGroup: '0',
  jobId: '0',
  start: 0,
  length: 10,
  logStatus: -1,
  filterTime: '',
  timeScope: []
})

const tableKey = ref(0)
const detailTailTimer = ref(null)
const jobLogDetail = ref({
  logContent: ''
})

const pickerOptions = ref({
  shortcuts: [{
    text: '今日',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)

      end.setDate(end.getDate() + 1)
      end.setHours(0)
      end.setMinutes(0)
      end.setSeconds(0)
      end.setTime(end.getTime() - 1000)
      picker.$emit('pick', [start, end]);
    }
  },{
    text: '最近一周',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)

      end.setDate(end.getDate() + 1)
      end.setHours(0)
      end.setMinutes(0)
      end.setSeconds(0)
      end.setTime(end.getTime() - 1000)
      picker.$emit('pick', [start, end]);
    }
  }, {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setDate(end.getDate() + 1)
      end.setHours(0)
      end.setMinutes(0)
      end.setSeconds(0)
      end.setTime(end.getTime() - 1000)
      picker.$emit('pick', [start, end]);
    }
  }, {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setDate(end.getDate() + 1)
      end.setHours(0)
      end.setMinutes(0)
      end.setSeconds(0)
      end.setTime(end.getTime() - 1000)
      picker.$emit('pick', [start, end]);
    }
  }]
})

const clearForm = ref({
  jobGroup: '0',
  jobId: '0',
  type: 1
})

const rules = {
  groupListData: [{required: true, message: '请选择执行器', trigger: 'blur'}],
  jobId: [{required: true, message: '请选择任务', trigger: 'blur'}],
  type: [{required: true, message: '请选择时间段', trigger: 'blur'}]
}

const getLogList = async () => {
  let params = JSON.parse(JSON.stringify(queryParams.value))
  if (params.timeScope.length > 0) {
    params.filterTime = params.timeScope[0] + ' - ' + params.timeScope[1]
    params.timeScope = null
    params.currentPage = null
  }
  
  try {
    const res = await getLogsList(params)
    const { data, recordsTotal } = res
    listLoading.value = false
    logTableList.value = data
    total.value = recordsTotal
    if (total.value === 0) {
      ElMessage({
        message: '检索结果为空',
        type: 'warning'
      })
    }
  } catch (err) {
    console.log(err)
  }
}

const fetchGroupList = async () => {
  try {
    const res = await getGroupList(qs.stringify(queryParams.value))
    const { data, recordsTotal } = res
    groupListData.value = data
    if (recordsTotal === 0) {
      ElMessage({
        message: '执行器列表为空,需要先创建执行器',
        type: 'warning'
      })
      return
    }
  } catch (err) {
    console.log(err)
  }
}

const groupChange = () => {
  queryParams.value.jobId = '0'
  if (queryParams.value.jobGroup !== '0') {
    getJobsByGroupLogs(queryParams.value.jobGroup).then(res => {
      const {code, content} = res
      if (res.code === 200) {
        jobs.value = content
      }
    }).catch(function (err) {
      console.log(err.message)
    })
  }
}

const groupClearChange = () => {
  clearForm.value.jobId = '0'
  if (clearForm.value.jobGroup !== null) {
    getJobsByGroupLogs(clearForm.value.jobGroup).then(res => {
      const {code, content} = res
      if (res.code === 200) {
        clearJobs.value = content
      }
    }).catch(function (err) {
      console.log(err.message)
    })
  }
}

const handleStopJob = (id) => {
  stopJob(id).then(res => {
    const {code, msg} = res
    if (code === 200) {
      ElMessage({
        message: '终止成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '终止失败',
        type: 'warning',
      })
    }
  }).catch(function (err) {
    console.log(err.message)
  })
}

const exeLogDetail = (row) => {
  let params={
    'executorAddress':row.executorAddress,
    'triggerTime': new Date(row.triggerTime).getTime(),
    'logId': row.id,
    'fromLineNum': 1
  }
  logTail(params)
  detailTailTimer.value = setInterval(() => {
    getJobDetail(params).then(res => {
      jobLogDetail.value = res.content
      if (res.code === 200) {
        dialogFormVisible.value = true
      } else {
        ElMessage({
          message: '查询失败',
          type: 'warning',
        })
      }
    }).catch(function (err) {
      console.log(err.message)
    })
  },2000)
  console.info(detailTailTimer.value)
}

const logTail = (params) => {
  getJobDetail(params).then(res => {
    jobLogDetail.value = res.content
    if (res.code === 200) {
      dialogFormVisible.value = true
    } else {
      ElMessage({
        message: '查询失败',
        type: 'warning',
      })
    }
  }).catch(function (err) {
    console.log(err.message)
  })
}

const onCloseDetail = () => {
  if (detailTailTimer.value != null){
    detailTailTimer.value = null
    clearInterval(detailTailTimer.value)
  }
}

const clearJobLogs = () => {
  clearLogDialog.value = true
}

const exeClearLogs = () => {
  const formRef = ref(null)
  formRef.value.validate((valid) => {
    if (valid) {
      clearLogs(clearForm.value).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: '清除成功',
            type: 'success',
          })
          clearLogDialog.value = false
          handleRefresh()
        } else {
          ElMessage({
            message: '清除失败',
            type: 'warning',
          })
        }
      }).catch(function (err) {
        console.log(err.message())
      })
    }
  })
}

const handleFilter = () => {
  queryParams.value.start = 1
  getLogList()
}

const handleSizeChange = (val) => {
  queryParams.value.length = val
  getLogList()
}

const handleCurrentChange = (val) => {
  queryParams.value.start = (val - 1) * queryParams.value.length
  getLogList()
}

const handleRefresh = () => {
  logTableList.value = null
  total.value = null
  queryParams.value.start = 0
  getLogList()
}

const triggerMsgDetail = (row) => {
  ElMessage.alert(row.triggerMsg, '调度备注', {
    dangerouslyUseHTMLString: true,
    closeOnPressEscape: true
  }).catch(() => {})
}

const jobDetail = (row) => {
  let desc = '执行器地址：'+row.executorAddress + '<br>' +
    'JobHandler：' + row.executorHandler + '<br>' +
    '任务参数：' + row.executorParam
  ElMessage.alert(desc, '任务描述', {
    dangerouslyUseHTMLString: true,
    closeOnPressEscape: true
  }).catch(() => {})
}

watch(() => jobLogDetail.value.logContent, (val, oldVal) => {
  const reg = RegExp(".*xxl-job job callback finish.\\n$")
  if (val.match(reg) && detailTailTimer.value != null) {
    clearInterval(detailTailTimer.value)
    detailTailTimer.value = null
  }
})

onMounted(() => {
  getLogList()
  fetchGroupList()
})
</script>

<style rel="stylesheet/scss" lang="scss" slot-scope>
  .app-container {
    padding: 20px;
  }

  .pagination-container {
    margin-top: 30px;
  }

  .fitersLine {
    .el-select .el-input{
      width: 135px;
    }
  }
  .detail-dialog{
    pre{
      overflow: auto;
      word-break: break-all;
      word-wrap: break-word;
      display: block;
      font-size: 12px;
      font-weight: 400;
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .clear-log-form-view {
    .el-select {
      width: 80%;
    }
  }

  .sucColor {
    color: seagreen;
  }

  .failColor {
    color: #f56c6c;
  }

  .top {
    padding: 10px;
  }

  .el-form--inline .el-form-item {
    margin-right: 2px;
  }

  .drop-down-view {
    .el-dropdown {
      vertical-align: top;
    }

    .el-dropdown + .el-dropdown {
      margin-left: 15px;
    }

    .el-icon-arrow-down {
      font-size: 12px;
    }

    .el-button {
      padding: 8px 7px;
    }

  }

  .el-button--mini {
    padding: 7px 10px;
  }

  .el-button + .el-button {
    margin-left: 1px;
  }

  .dialog-detail-view {
    .el-form-item {
      margin-bottom: 0px;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__label {
      line-height: 30px;
    }
  }

  .el-dialog__header {
    padding-bottom: 0;
  }

  .el-dialog__body {
    padding: 0
  }

  .createPost-main-container {
    padding: 20px 0 !important;
  }

  .fitersLine {
    .el-form-item__content {
      margin-left: 0 !important
    }
    .el-form-item__label {
      min-width: auto !important;
    }
    .el-select {
      margin-top: 3px;
    }
  }
</style>
